package com.toycloud.interceptor;

import com.toycloud.system.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 * 注意：此拦截器会同时验证当前用户有效期自动刷新有效期
 *
 * @author ruoyi
 */
@Component
@Slf4j
public class HeaderInterceptor implements AsyncHandlerInterceptor
{
    public static final String APPID = "wdiON2lqQGqMjBHA70Rce";
    private final JwtUtil jwtUtil = new JwtUtil();

    @Value("${spring.profiles.active}")
    private String activeProfile;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        log.info("activeProfile: {}", activeProfile);
        if ("prod".equals(activeProfile)) {
            if (!(handler instanceof HandlerMethod))
            {
                return true;
            }
            String authorizationHeader = request.getHeader("Authortoken");
            if (authorizationHeader != null && authorizationHeader != "") {
                if (jwtUtil.isTokenExpired(authorizationHeader)) {
                    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//                    response.sendRedirect("/user/login");
                    return false;
                }

                // 解密 JWT token，获取用户信息
                String loginUser = jwtUtil.extractUsername(authorizationHeader);
                if (loginUser != null) {
                    request.setAttribute("Authorization", loginUser); // 这里替换成新的常量名称
                }

            } else {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//                response.sendRedirect("/user/login");
                return false;
            }
        }
        return true;
    }

}
